<template>
  <div class="wrap">
    <div class="head">
      <span @click="backPath()" style="cursor: pointer;"><i class="el-icon-arrow-left"></i>返回</span>
      <span class="primary">分享设置</span>
    </div>
    <div class="mian">
      <el-form :model="params" ref="ruleForm" label-width="140px" size="small">
        <el-form-item label="分享设置" required style="margin-bottom: 0">
          <el-row type="flex">
            <el-select v-model="diyPrice">
              <el-option label="固定金额" :value="1" />
              <el-option label="随机金额" :value="2" />
            </el-select>
            <span style="margin:0 5px;">,</span>
            <el-form-item prop="min" v-if="diyPrice === 1" :rules="[{ required: true, message: '请输入金额'}]">
              <el-input-number :min='0.1' :max='999' :precision='1' v-model="params.min" /> 元
            </el-form-item>
            <el-row type="flex" v-if="diyPrice == 2">
              <span style="margin:0 5px;">随机金额最少</span>
              <el-form-item prop="min" :rules="[{ required: true, message: '请输入金额' }]">
                <el-input-number v-model="params.min" :min='0' :max='params.max ? params.max : 999' :precision='0' />
              </el-form-item>
              <span style="margin:0 5px;">元,最多</span>
              <el-form-item prop="max" :rules="[{ required: true, message: '请输入金额' }]">
                <el-input-number v-model="params.max" :min='params.min ? params.min : 0' :max='999' :precision='0' />
              </el-form-item>
              <span style="margin-left:5px;">元通用红包</span>
            </el-row>
          </el-row>
        </el-form-item>
        <el-form-item label="红包设置" required style="margin-bottom: 0">
          <el-row type="flex">
            <span style="margin-right:5px;">共</span>
            <el-form-item prop="num" :rules="[{ required: true, message: '请输入人数'}]">
              <el-input-number :min='0' :max='999' :precision='0' v-model="params.num" />
            </el-form-item>
            <span style="margin:0 5px;">人, 第</span>
            <el-form-item prop="maxrednum" :rules="[{ required: true, message: '请输入特定红包顺序' }]">
              <el-input-number v-model="params.maxrednum" :min='0' :max='params.num ? params.num : 0' :precision='0' />
            </el-form-item>
            <span style="margin:0 5px;">人特定</span>
            <el-form-item prop="maxredamount" :rules="[{ required: true, message: '请输入金额' }]">
              <el-input-number  v-model="params.maxredamount" :min='0' :max='999' :precision='1' />
            </el-form-item>
            <span style="margin-left:5px;">元</span>
          </el-row>
        </el-form-item>
        <el-form-item label="使用条件" required style="margin-bottom: 0">
          <el-form-item prop="fulls" :rules="[{ required: true, message: '请输入金额' }]">
            消费满 <el-input-number :min='0.1' :max='999' :precision='1' v-model="params.fulls" /> 元可用
          </el-form-item>
        </el-form-item>
        <el-form-item label="红包有效期" required style="margin-bottom: 0">
          <el-form-item prop="redvalidday" :rules="[{ required: true, message: '请输入金额' }]">
            <el-input-number :min='1' :max='999' :precision='0' v-model="params.redvalidday" /> 天
          </el-form-item>
        </el-form-item>
        <el-form-item label="开启分区域" v-if="childrenAgentId.length > 0">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="params.agentids" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in childrenAgentId" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <div class="msg">
          <p class="head">说明:</p>
          <p class="item">1.用户下单支付后，可分享一个多人红包。</p>
          <p class="item">2.该红包支持{{childrenAgentId.length ? '开启区域' : '全平台'}}，全类目使用（跑腿订单除外）。</p>
        </div>
        <el-form-item>
          <el-button @click="backPath()">取消</el-button>
          <el-button type="primary" plain @click="submitForm('ruleForm', 0)" :loading="isloadingUpdate">仅保存</el-button>
          <el-button type="primary" @click="submitForm('ruleForm', 1)" :loading="isloadingUpdate">保存并开启</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { redEnvelopeSave, redEnvelopeUpload, redEnvelopeInfo } from '@/api/activity'
import { agentSubList } from '@/api/com'
export default {
  data() {
    return {
      params: {
        type: 2,
        min: undefined,
        max: undefined,
        fulls: undefined,
        num: undefined, // 红包数量
        maxredamount: undefined, // 最大红包
        maxrednum: undefined, // 第几个红包最大
        redvalidday: undefined, // 红包有效期
        agentids: []
      },
      checkAll: false,
      isIndeterminate: false,
      childrenAgentId: [],
      diyPrice: 1, // 固定金额或随机金额
      isloadingUpdate: false
    }
  },
  methods: {
    backPath() {
      this.$router.back()
    },
    handleCheckAllChange(val) {
      this.params.agentids = val ? this.childrenAgentId.map(i => i.id) : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.childrenAgentId.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.childrenAgentId.length
    },
    getDetail(id, agentid) { // 获取活动详情
      const params = { id, agentid }
      redEnvelopeInfo(params).then(res => {
        if (res.success) {
          let min = undefined
          let max = undefined
          if (res.data.redamount) {
            if (res.data.redamount.indexOf(',') > -1) {
              this.diyPrice = 2
              min = res.data.redamount.split(',')[0]
              max = res.data.redamount.split(',')[1]
            } else {
              min = res.data.redamount
              this.diyPrice = 1
            }
          }
          this.params = {
            type: 2, min, max,
            agentids: res.data.agentids ? res.data.agentids.split(',').map(i => parseInt(i)) : [],
            fulls: res.data.fulls || undefined,
            num: res.data.num || undefined, // 红包数量
            maxredamount: res.data.maxredamount || undefined, // 最大红包
            maxrednum: res.data.maxrednum || undefined, // 第几个红包最大
            redvalidday: res.data.redvalidday || undefined // 红包有效期
          }
          this.handleCheckedCitiesChange(this.params.agentids)
        }
      })
    },
    submitForm(formName, type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isloadingUpdate = true
          const params = { ...this.params, agentid: this.query.agentid, enable: type }
          params.agentids = params.agentids.length ? params.agentids.join(',') : null
          if (this.diyPrice === 1) {
            params.redamount = params.min
          } else {
            params.redamount = `${params.min},${params.max}`
          }
          delete params.min
          delete params.max
          if (this.query.id) {
            params.id = this.query.id
            redEnvelopeUpload(params).then(res => {
              if (res.success) {
                this.backPath()
              }
            }).finally(() => { this.isloadingUpdate = false })
          } else {
           redEnvelopeSave(params).then(res => {
              if (res.success) {
                this.backPath()
              }
            }).finally(() => { this.isloadingUpdate = false })
          }
        } else {
          return false
        }
      })
    },
    getAgentSubList(agentId) { // 获取子区域
      agentSubList({ agentId }).then(res => {
        if (res.success) {
          this.childrenAgentId = res.data.children || []
        }
      })
    }
  },
  mounted() {
    this.query = this.$route.query
    if (this.query.agentid) {
       this.getAgentSubList(this.query.agentid)
      if (this.query.id) {
        this.getDetail(this.query.id, this.query.agentid)
      }
    } else {
      this.$router.back()
    }
  }
}
</script>
<style lang="scss" scoped>
  .wrap {
    .head{
      height: 40px;
      line-height: 40px;
      .primary{
        margin-left: 20px;
        font-weight: 600;
      }
    }
    .mian{
      padding: 40px 0 0 0;
    }
    .msg{
      margin: 30px 0;
      padding: 10px;
      border: 1px solid #ccc;
      .head{
        font-size: 16px;
        font-weight: 600;
        line-height: 40px;
      }
      .item{
        text-indent: 2em;
        line-height: 30px;
        color: #999;
      }
    }
  }
</style>